import paramiko
import sys
import getpass
import threading
import os

def rcmd(host, user, passwd, cmds):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host, username=user, password=passwd)
    stdin, stdout, stderr = ssh.exec_command(cmds)
    out = stdout.read()
    err = stderr.read()
    if out:   # 如果out非空
        print(f'[{host}] \033[32;1mOUT\033[0m:\n{out.decode()}')
    if err:
        print(f'[{host}] \033[31;1mERROR\033[0m:\n{err.decode()}')
    ssh.close()

if __name__ == '__main__':
    # python3 rcmd.py servers.txt 'sleep 3; id root'
    # 判断用户是否按要求格式运行了程序
    if len(sys.argv) != 3:
        print(f"用法: {sys.argv[0]} 主机文件 '命令'")
        exit(1)

    # 判断文件是否存在
    if not os.path.isfile(sys.argv[1]):
        print(f'没有那个文件: {sys.argv[1]}')
        exit(2)

    ipfile = sys.argv[1]
    user = 'root'
    passwd = getpass.getpass()
    cmds = sys.argv[2]
    with open(ipfile) as fobj:
        for line in fobj:
            ip = line.strip()  # 去掉行尾的\n
            # rcmd(ip, user, passwd, cmds)
            t = threading.Thread(target=rcmd, args=(ip, user, passwd, cmds))
            t.start()
